<script setup>
    import reserveApi from "@/api/reserve.js";
    import {ref} from "vue";
    import {ElMessage, ElMessageBox} from "element-plus";
    import {Plus} from '@element-plus/icons-vue'
    import userApi from "@/api/user.js";
    import courseApi from "@/api/course.js";

    //数据表格
    const list = ref([])//当前页数据
    const total = ref(0)//总条目数

    //分页信息和搜索条件
    const reserveQuery = ref({
        name: '',
        reserveId: '',
        courseId: '',
        page: 1,
        limit: 10
    })

    /* reserveApi.list(reserveQuery.value).then(result => {
         list.value = result.data.records//当前页数据
         total.value = result.data.total//总条目数
     })*/

    //调用reserveApi.list查找所有预约信息
    const loadData = () => {//加载数据，分页查找
        reserveApi.list(reserveQuery.value).then(result => {
            if(result.code == 0) {
                list.value = result.data.records//当前页数据
                total.value = result.data.total//总条目数
            }
        })
    }

    loadData()//调用

    //条件查找，拼接条件在后端mapper已经实现
    const onSearch = () => {
        reserveQuery.value.page = 1
        loadData()
    }

    //重置搜索框为空
    const reset = () => {
        reserveQuery.value.name = ''
        reserveQuery.value.reserveId = ''
        reserveQuery.value.courseId = ''
        reserveQuery.value.userId = ''
        reserveQuery.value.beginUpdateTime = ''
        reserveQuery.value.endUpdateTime = ''
    }

    //按id删除
    const deleteById = (id) => {
        ElMessageBox.confirm(
            '您确认要删除吗?',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(() => {
            reserveApi.deleteById(id).then(result => {
                if (result.code == 0) {
                    ElMessage.success(result.msg)
                    loadData()
                } else {
                    ElMessage.error(result.msg)
                }
            })
        })
    }

    //批量删除
    //1.双向绑定将前台勾选的id存进数组
    const ids = ref([])
    const handleSelectionChange = (rows) => {
        console.log('多选',rows)
        ids.value = rows.map(row => row.id)
        console.log(ids.value)
    }
    //执行批量删除
    const deleteAll = () => {
        ElMessageBox.confirm(
            '您确认要删除吗?',
            '警告',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(() => {
            reserveApi.deleteAll(ids.value).then(result => {
                if (result.code == 0) {
                    ElMessage.success(result.msg)
                    loadData()//成功后重新加载数据，分页查找
                } else {
                    ElMessage.error(result.msg)
                }
            })
        })
    }

    //添加、编辑
    const dialogFormVisible = ref(false)//点击前默认不显示
    const reserve = ref({//ref:双向绑定，reserve为前台输入要添加编辑的对象，ref里的参数vue动态地帮我加上去了
        length: 1,
        maxCount: 5
    })
    //添加
    const showAddDialog = () => {
        reserve.value = {
            length: 1,
            maxCount: 5
        }  //本来是reserve.value = {} 清空对话框上一次留下的数据，否则会由于双向绑定把上一次添加的数据回显，但这里的课程时长length和最大人数maxCount要给一个默认值，所有赋了值
        dialogFormVisible.value = true//触发点击事件showAddDialog后显示
    }

    //编辑（更新）
    const showUpdateDialog = (id) => {
        dialogFormVisible.value = true//弹出对话框
        reserve.value = {
            length: 1,
            maxCount: 5
        }  //本来是reserve.value = {} 清空对话框上一次留下的数据，否则会由于双向绑定把上一次添加的数据回显，但这里的课程时长length和最大人数maxCount要给一个默认值，所有赋了值
        reserveApi.selectById(id).then(result => {
            if (result.code == 0) {//result.code==0 证明查找成功
                reserve.value = result.data //result.data查找结果的值（旧值）赋值给双向绑定的reserve.value（新值）
            }
        })
    }
    //添加编辑判断执行
    const addOrUpdate = () => {
        if (reserve.value.id) {
            reserveApi.update(reserve.value).then(result => {
                if (result.code == 0) { //js里有非空值就代表true
                    ElMessage.success(result.msg)
                    dialogFormVisible.value = false//更新完自动关闭对话框
                    loadData()//成功后重新加载数据，分页查找
                } else {
                    ElMessage.error(result.msg)
                }
            })
        } else {
            reserveApi.add(reserve.value).then(result => {
                if (result.code == 0) {
                    ElMessage.success(result.msg)
                    dialogFormVisible.value = false//添加完自动关闭对话框
                    loadData()//成功后重新加载数据，分页查找
                } else {
                    ElMessage.error(result.msg)
                }
            })
        }
    }

    //el-switch状态切换
    const handleSwitchChange = (row) => {
        console.log(row)
        //使用update,不定义新接口
        const reserve = {}
        reserve.id = row.id
        reserve.status = row.status
        reserveApi.update(reserve).then(result => {
            if (result.code == 0) {
                ElMessage.success(result.msg)
            } else {
                ElMessage.error(result.msg)
            }
        })
        //定义新接口updateStatus
        /*reserveApi.updateStatus(row.id,row.status).then(result => {
            if (result.code == 0) {
                ElMessage.success(result.msg)
            } else {
                ElMessage.error(result.msg)
            }
        })*/
    }

    //查找所有的用户
    const userList = ref([])
    userApi.selectAll().then(result => {
        if (result.code == 0) {
            userList.value = result.data
        }
    })

    //查找所有的课程
    const courseList = ref([])
    courseApi.selectAll().then(result => {
        if (result.code == 0) {
            courseList.value = result.data
        }
    })

    //下拉事件
    const selectChange = (value) => {
        console.log(value)
    }
</script>

<template>
    <el-card class="">
        <!-- header表头 -->
        <template #header>
            <div class="header">
                <el-button type="primary" @click="showAddDialog">添加</el-button>
                <el-button type="primary" @click="deleteAll">批量删除</el-button>
            </div>
        </template>
        <el-form :inline="true">
            <el-form-item label="名字">
                <el-select @change="selectChange" v-model="reserveQuery.userId" placeholder="请选择用户" clearable
                           style="width: 240px">
                    <el-option
                        v-for="user in userList"
                        :key="user.id"
                        :label="user.name"
                        :value="user.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="课程">
                <el-select @change="selectChange" v-model="reserveQuery.courseId" placeholder="请选择课程" clearable
                           style="width: 240px">
                    <el-option
                        v-for="course in courseList"
                        :key="course.id"
                        :label="course.name"
                        :value="course.id"
                    />
                </el-select>
            </el-form-item>
            <!--reserveQuery里没有beginUpdateTime这两个属性，后端java代码CourseQuery对象里一定要加上，但是vue很智能会自动加上，所以前端代码ref里不用写也可以-->
            <el-form-item label="更新时间" :label-width="100">
                 <el-date-picker
                    v-model="reserveQuery.beginUpdateTime"
                    type="datetime"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="开始时间"
                />
                <el-date-picker
                    v-model="reserveQuery.endUpdateTime"
                    type="datetime"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="结束时间"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSearch">搜索</el-button>
                <el-button type="warning" @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
        <!-- 表中间遍历输出表格内容 -->
        <el-table :data="list" style="width: 100%" ref="multipleTableRef" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"/>
            <el-table-column fixed prop="id" label="ID"/>
            <el-table-column prop="userId" label="用户id"/>
            <el-table-column prop="userName" label="用户"/>
            <el-table-column prop="courseId" label="课程id"/>
            <el-table-column prop="courseName" label="课程"/>
            <el-table-column prop="score" label="评分" width="180px"/>
            <el-table-column prop="comment" label="评论"/>
            <el-table-column prop="status" label="状态">
                <template #default="scope">
                    <el-switch
                        v-model="scope.row.status"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                        :active-value="1"
                        :inactive-value="0"
                        active-text="预约中"
                        inactive-text="已完课"
                        inline-prompt
                        @change="handleSwitchChange(scope.row)"
                    />
                </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="更新时间" width="180px"/>
            <el-table-column align="center" width="200px" fixed="right" label="操作">
                <template #default="{ row }"><!--解构赋值-->
                    <el-button size="small" type="primary" @click="showUpdateDialog(row.id)">编辑</el-button>
                    <el-button size="small" type="danger" @click="deleteById(row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!--底部分页-->
        <el-pagination
            v-model:current-page="reserveQuery.page"
            v-model:page-size="reserveQuery.limit"
            :page-sizes="[10, 20, 30, 40]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @change="loadData"
            style="margin-top: 20px; justify-content: flex-end"
        />
    </el-card>


    <!--添加、编辑弹出框-->
    <el-dialog v-model="dialogFormVisible" :title="title" width="60%" :lock-scroll="false">
        <el-form :model="reserve">
            <el-form-item label="用户" :label-width="80">
                <el-select v-model="reserve.userId" placeholder="请选择用户" style="width: 240px">
                    <el-option
                        v-for="user in userList"
                        :key="user.id"
                        :label="user.name"
                        :value="user.id"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="课程" :label-width="80">
                <el-select v-model="reserve.courseId" placeholder="请选择课程" style="width: 240px">
                    <el-option
                        v-for="course in courseList"
                        :key="course.id"
                        :label="course.name"
                        :value="course.id"
                    />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="addOrUpdate">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style scoped>
    .avatar-uploader .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>

<style>
    .avatar-uploader .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
    }
</style>